package by.amakarevich.services.impl;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import by.amakarevich.dataaccess.ProductDao;
import by.amakarevich.datamodel.Product;
import by.amakarevich.datamodel.enums.Category;
import by.amakarevich.services.ProductService;

@Service
public class ProductServiceImpl implements ProductService {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductServiceImpl.class);

	@Inject
	private ProductDao dao;
	
	@Value(value="${rootImagesFolfer}")
	private String rootFolder;

	@PostConstruct
	private void init() {
		// this method will be called by Spring after bean instantiation. Can be
		// used for any initialization process.
		LOGGER.info("Instance of ProductService is created. Class is: {}", getClass().getName());
	}

	@Override
	public Product get(Long id) {
		Product entity = dao.getById(id);
		return entity;
	}

	@Override
	public void saveOrUpdate(Product product) {
		if (product.getId() == null) {
			LOGGER.debug("Save new: {}", product);
			dao.insert(product);
		} else {
			LOGGER.debug("Update: {}", product);
			dao.update(product);
		}
	}

	@Override
	public void delete(Product product) {
		LOGGER.debug("Remove: {}", product);
		dao.delete(product.getId());

	}

	@Override
	public void deleteAll() {
		LOGGER.debug("Remove all products");
		dao.deleteAll();
	}
	
	@Override
    public List<Product> getAllProductsByCompany(String company, Category category) {
        return dao.getAllProductsByCompany(company, category);
    }
	
	public String getRootFolder() {
		return rootFolder;
	}
	
	@Override
    public List<Product> getAllProductsByCategory(Category category) {
        return dao.getAllProductsByCategory(category);
    }
	@Override
	public List<Product> getSortedAllProduct(SingularAttribute<Product, ?> attr, boolean ascending, int startRecord, int pageSize, Category category){
    	return dao.getSortedAllProduct(attr, ascending, startRecord, pageSize, category);
    }
	
	@Override
	public Long getCount(Category category){
		return dao.getCount(category);
	}
	
	@Override
	public List<Product> getSortedAllProduct(SingularAttribute<Product, ?> attr, boolean ascending,
			int startRecord, int pageSize, Category category, String company){
		return dao.getSortedAllProduct(attr, ascending, startRecord, pageSize, category, company);
	}
	
	@Override
	public Long getCount(Category category, String company){
		return dao.getCount(category, company);
	}
}
